package com.avic.rong.questionOrAnswer.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.activity.login.LoginPhoneActivity;
import com.avic.rong.questionOrAnswer.DialogShare;
import com.avic.rong.questionOrAnswer.ShareUtilCallBack;
import com.avic.rong.questionOrAnswer.api.CancelnCollectionApi;
import com.avic.rong.questionOrAnswer.api.CollectApi;
import com.avic.rong.questionOrAnswer.api.DeleteQuestionApi;
import com.avic.rong.questionOrAnswer.api.QuestionCollectNumApi;
import com.avic.rong.questionOrAnswer.api.UpdateDataQuestionsApi;
import com.avic.rong.questionOrAnswer.api.WetherAnsweApi;
import com.avic.rong.questionOrAnswer.bean.IsAnswerBean;
import com.avic.rong.questionOrAnswer.bean.UpdataDataQuestionBean;
import com.avic.rong.questionOrAnswer.bean.WebCollectBean;
import com.avic.rong.questionOrAnswer.bean.WebShareBean;
import com.avic.rong.userOrder.event.InformUpdate;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DialogCustom;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.SmartHttp;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.ScrollWebViewListion;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.AppUtils;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.tsy.sdk.myokhttp.response.IResponseHandler;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import okhttp3.Response;
import wendu.dsbridge.OnReturnValue;

public class QuestionDetailsActivity extends BaseActivity implements ShareUtilCallBack {



    @BindView(R.id.btn_comment_publish)
    TextView btnCommentPublish;
    @BindView(R.id.btn_collect)
    ImageView btnCollect;
    @BindView(R.id.collect_number)
    TextView collectNumber;
    @BindView(R.id.btn_bottom_share)
    ImageView btnBottomShare;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.webview)
    ScrollWebViewListion web;
    private DialogShare dialogShare;
    @BindView(R.id.rl_collect)
    RelativeLayout rl_collect;

    private boolean isFinished;
    private WebSettings settings;
    private String queID;
    private WebCollectBean webCollectBean;

    private int ANSWER_SHOW=100;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_question_details;
    }

    @Override
    protected void initView() {
        if (TextUtils.isEmpty(getIntent().getStringExtra("queID"))) {
            finish();
            return;
        } else {
            queID = getIntent().getStringExtra("queID");
        }
        tvTitle.setText("问题详情");
        ivRight.setClickable(false);
        web.setInitialScale(100);
//        web.setWebChromeClient(new MyWebChromeClient());
//        web.setWebViewClient(new MyWebViewClient());


        settings = web.getSettings();


        // 设置加载进来的页面自适应手机屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);


        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        settings.setDisplayZoomControls(false);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);


        web.addJavascriptObject(this, null);
        web.setOnScrollChangeListener(new ScrollWebViewListion.OnScrollChangeListener() {
            @Override
            public void onPageEnd(int l, int t, int oldl, int oldt) {
                web.callHandler("loadMore", new OnReturnValue<String>() {
                    @Override
                    public void onValue(String retValue) {

                    }
                });
            }

            @Override
            public void onPageTop(int l, int t, int oldl, int oldt) {

            }

            @Override
            public void onScrollChanged(int l, int t, int oldl, int oldt) {

            }
        });

        web.loadUrl(AppUtils.BASE_URL + "question/detail?queId=" + queID + "&token=" + URLEncoder.encode(getSharedPreferencesUtil().getLogintoken()));

        rl_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btnCollect.isSelected()) {
                    unCollectReq(queID, context);
                } else {
                    collectReq(queID, context);
                }
            }
        });
        btnCommentPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isAnswer();
            }
        });

        initData();
    }

    private void isAnswer() {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("token",getSharedPreferencesUtil().getLogintoken());
            map.put("queId",queID);
            final WetherAnsweApi wetherAnsweApi = new WetherAnsweApi(this, simpleOnNextListener);
            wetherAnsweApi.setCache(false);
            wetherAnsweApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(wetherAnsweApi);
        }else {
            startActivity(LoginPhoneActivity.queryIntent(this));
        }
    }

    private void initData() {

    }
    //是否回答过问题
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(QuestionDetailsActivity.this,subjects.getMsg());
                return;
            }
            IsAnswerBean isAnswerBean= (IsAnswerBean) subjects.getData();
            if (isAnswerBean!=null){
//                if (isAnswerBean.isResult()){
                    Intent intent = new Intent(context, AnswerActivity.class);
                    intent.putExtra(AnswerActivity.QUEID, queID);
                    startActivityForResult(intent,ANSWER_SHOW);
//                }else {
////                    context.startActivity(AnswerDetailsActivity.queryIntent(context,queID));
//                    ToastTools.showToast(context,"你已回答过此问题请不要重复回答");
//                }
            }


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx",e.getMessage());
        }
    };
    class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.i(TAG, "onPageStarted " + url);

        }

        @Override
        public void onPageFinished(WebView view, String url) {

            isFinished = true;


        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            return true;
        }

//        @Override
//        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//            handler.proceed();  // 接受所有网站的证书
//            super.onReceivedSslError(view, handler, error);
//        }
    }

    class MyWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Log.i(TAG, "onReceivedTitle " + title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
//            progressBar.setProgress(newProgress);
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.d(TAG, "onJsAlert " + message);
            return super.onJsAlert(view, url, message, result);
        }
    }


    @Override
    protected void addListener() {
        btnBottomShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                questionNum();

                //分享
                if (dialogShare == null) {
                    dialogShare = new DialogShare(QuestionDetailsActivity.this, QuestionDetailsActivity.this);
                }
                if (webCollectBean!=null){
                    if (webCollectBean.getImgs()!=null&&!TextUtils.isEmpty(webCollectBean.getImgs().get(0))&&webCollectBean.getImgs().size()>0){
                        dialogShare.showDialog("融融上的这个问题很有意思，邀请你一起参与讨论", webCollectBean.getTitle(), webCollectBean.getUrl(),  webCollectBean.getImgs().get(0));
                    }else {
                        dialogShare.showDialog("融融上的这个问题很有意思，邀请你一起参与讨论", webCollectBean.getTitle(), webCollectBean.getUrl(), "");
                    }

                }
            }
        });
    }

    @JavascriptInterface
    public void userLogin(Object msg) {

        if (!SharedPreferencesUtil.isLogin()){
            startActivity(LoginPhoneActivity.queryIntent(this));
        }

    }

    @JavascriptInterface
    public void shareAnswer(Object msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Gson gson = new Gson();
                Log.e("shareAnswer",msg.toString());
                WebShareBean webShareBean = gson.fromJson(msg.toString(), WebShareBean.class);

                Log.e("====shareAnswer", "调用了" + msg);
                //分享
                if (dialogShare == null) {
                    dialogShare = new DialogShare(QuestionDetailsActivity.this, QuestionDetailsActivity.this);
                }
                if (webShareBean != null) {

                    answerNum(webShareBean.getAnsId());//记录回答分享数据

                    if (webShareBean.getImgs()!=null&&!TextUtils.isEmpty(webShareBean.getImgs().get(0))&&webShareBean.getImgs().size()>0){
                        dialogShare.showDialog("融融上的这个回答很有意思，邀请你一起参与讨论", webShareBean.getDesc(), webShareBean.getUrl(), webShareBean.getImgs().get(0));
                    }else {
                        dialogShare.showDialog("融融上的这个回答很有意思，邀请你一起参与讨论", webShareBean.getDesc(), webShareBean.getUrl(),"");
                    }

                }
            }
        });
    }


    private void answerNum(int answerId){

        SmartHttp.getHttpTwo(AppUtils.BASE_URL + "answer/shareNum?ansId=" + answerId , new IResponseHandler() {
            @Override
            public void onSuccess(Response response) {
                Logger.i("----------onSuccess");
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                Logger.i("----------onFailure");
            }

            @Override
            public void onProgress(long currentBytes, long totalBytes) {
                Logger.i("----------onProgress");
            }
        });

    }


    private void questionNum(){

        SmartHttp.getHttpTwo(AppUtils.BASE_URL + "question/shareNum?queId=" + queID , new IResponseHandler() {
            @Override
            public void onSuccess(Response response) {
                Logger.i("----------onSuccess");
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                Logger.i("----------onFailure");
            }

            @Override
            public void onProgress(long currentBytes, long totalBytes) {
                Logger.i("----------onProgress");
            }
        });

    }

    @JavascriptInterface
    public void addComment(Object msg) {

        if (TextUtils.isEmpty(getSharedPreferencesUtil().getLogintoken())) {
            startActivity(LoginPhoneActivity.queryIntent(this));
        } else {
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(msg.toString());
                String ansId = jsonObject.getString("ansId");
                startActivity(AnswerDetailsActivity.queryIntent(this, ansId));
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    @JavascriptInterface
    public String getPage(Object msg) {

        Gson gson = new Gson();
        webCollectBean = gson.fromJson(msg.toString(), WebCollectBean.class);
        if (webCollectBean != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (webCollectBean.isIsCollect()) {
                        btnCollect.setSelected(true);
                    } else {
                        btnCollect.setSelected(false);
                    }
                    collectNumber.setText(webCollectBean.getCollectNum() + "");
                }
            });

        }

        web.callHandler("closeDeepLink", new OnReturnValue<String>() {
            @Override
            public void onValue(String retValue) {

            }
        });
        Log.e("====initPage", "调用了" + msg);
//        handler.complete(getSharedPreferencesUtil().getLogintoken());
        return getSharedPreferencesUtil().getLogintoken();
    }

    @JavascriptInterface
    public void openAnswer(Object msg) {
        try {
            JSONObject jsonObject = new JSONObject(msg.toString());
            String ansId = jsonObject.getString("ansId");
            startActivity(AnswerDetailsActivity.queryIntent(this, ansId));
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    @JavascriptInterface
    public void editQuestion(Object msg) {
        updateDataQuestions();
    }
    @JavascriptInterface
    public void delQuestion(Object msg) {
        DialogCustom.showDoubleDialog(this, "", "确定要删除当前已发布的问题吗？", "取消", "确定", new DialogCustom.CustomDialogDouble() {
            @Override
            public void rightButtonClicked() {
                deleteQuestion();
            }

            @Override
            public void leftButtonClicked() {

            }
        });


    }

    @JavascriptInterface
    public void openUserCenter(Object msg){
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(msg.toString());
            String userId = jsonObject.getString("userId");
            Intent intent = new Intent(QuestionDetailsActivity.this, PersonalHomeActivity.class);
            intent.putExtra("homeUserID",userId);
            startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void updateDataQuestions() {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("queId",queID);
            final UpdateDataQuestionsApi updateDataQuestionsApi = new UpdateDataQuestionsApi(this, simpleOnNextListenerUpdateDataQuestions);
            updateDataQuestionsApi.setCache(false);
            updateDataQuestionsApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(updateDataQuestionsApi);
        }
    }
    //编辑提问
    HttpOnNextListener simpleOnNextListenerUpdateDataQuestions = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(QuestionDetailsActivity.this,subjects.getMsg());
                return;
            }
            UpdataDataQuestionBean updataDataQuestionBean = (UpdataDataQuestionBean) subjects.getData();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    startActivityForResult(QuestionActivity.queryIntent(QuestionDetailsActivity.this,updataDataQuestionBean),QuestionActivity.QUESTION_SHOW);
                }
            });



        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx",e.getMessage());

        }
    };



    private void deleteQuestion() {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("token",getSharedPreferencesUtil().getLogintoken());
            map.put("queId",queID);
            final DeleteQuestionApi deleteQuestionApi = new DeleteQuestionApi(this, simpleOnNextListenerDeleteQue);
            deleteQuestionApi.setCache(false);
            deleteQuestionApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(deleteQuestionApi);
        }
    }
    //删除提问
    HttpOnNextListener simpleOnNextListenerDeleteQue = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(QuestionDetailsActivity.this,subjects.getMsg());
                return;
            }
            InformUpdate informUpdate = new InformUpdate();
            informUpdate.setEventType(informUpdate.DELETE_QUESTION_INFORM);
            EventBus.getDefault().post(informUpdate);
            finish();


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx",e.getMessage());

        }
    };

    @Override
    public void shareSuccess() {

    }

    @Override
    public void shareFailed() {

    }

    @Override
    public void shareCancel() {

    }

    @Override
    protected void onDestroy() {

        if (web != null) {
            web.getSettings().setJavaScriptEnabled(false);
            web.clearHistory();
            web.removeAllViews();
            web.destroy();
        }

        EventBus.getDefault().unregister(this);
        super.onDestroy();


        System.gc();
    }

    public static Intent queryIntent(Context context, String queID) {
        Intent intent = new Intent(context, QuestionDetailsActivity.class);
        intent.putExtra("queID", queID);
        return intent;
    }

    private void collectReq(String contId, Context context) {
        Map<String, String> map = new HashMap<>();

        if (TextUtils.isEmpty(contId) && TextUtils.isEmpty(getSharedPreferencesUtil().getLogintoken())) {
            return;
        }
        map.put("targetId", contId + "");

        //收藏对象类型（1：软件服务  2：元器件 3：元器件审核备案 4：元器件试验检测  5：培训 6：标准 7：标准知识 8:企业 12:文章13:提问 14:回答）
        map.put("favoritesFlag", 13 + "");

        map.put("token", getSharedPreferencesUtil().getLogintoken());
        final CollectApi collectApi = new CollectApi(this, simpleOnNextListenerCollect);
        collectApi.setCache(false);
        collectApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(collectApi);
    }

    private void unCollectReq(String contId, Context context) {

        Map<String, String> map = new HashMap<>();

        if (TextUtils.isEmpty(contId) && TextUtils.isEmpty(getSharedPreferencesUtil().getLogintoken())) {
            return;
        }

        map.put("targetId", contId + "");

        //收藏对象类型（1：软件服务  2：元器件 3：元器件审核备案 4：元器件试验检测  5：培训 6：标准 7：标准知识 8:企业 12:文章13:提问 14:回答）
        map.put("favoritesFlag", 13 + "");

        map.put("token", getSharedPreferencesUtil().getLogintoken());
        final CancelnCollectionApi cancelnCollectionApi = new CancelnCollectionApi(this, simpleOnNextListenerUnCollect);
        cancelnCollectionApi.setCache(false);
        cancelnCollectionApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(cancelnCollectionApi);
    }

    //收藏
    HttpOnNextListener simpleOnNextListenerCollect = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_1000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            ToastTools.showToast(context, "收藏成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            collectNumber.setText(num + "");
            btnCollect.setSelected(true);
            questionCollectNum();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    //取消收藏
    HttpOnNextListener simpleOnNextListenerUnCollect = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            ToastTools.showToast(context, "取消收藏成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            collectNumber.setText(num + "");
            btnCollect.setSelected(false);
            questionCollectNum();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    private void questionCollectNum() {
        Map<String, String> map = new HashMap<>();

        if (TextUtils.isEmpty(queID)) {
            return;
        }
        map.put("queId", queID);

        final QuestionCollectNumApi questionCollectNumApi = new QuestionCollectNumApi(this, simpleOnNextListenerCollectNum);
        questionCollectNumApi.setCache(false);
        questionCollectNumApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(questionCollectNumApi);
    }

    //问题收藏变动
    HttpOnNextListener simpleOnNextListenerCollectNum = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
//                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==QuestionActivity.QUESTION_SHOW&&resultCode==RESULT_OK){
            web.reload();
        }else if (requestCode==ANSWER_SHOW&&resultCode==RESULT_OK){
            web.reload();
        }
        if (dialogShare != null) {
            dialogShare.initActivityResultSsoHandler(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (SharedPreferencesUtil.isLogin()){
          web.reload();
        }
    }

}
